const xlsx = require('node-xlsx');

const csv = require('csvtojson');
const iconv = require('iconv-lite');


class ExcelService {

    async readCsvToJson(csvFilePath) {
        return new Promise((resolve, reject) => {
            const converter = csv()
                .fromFile(csvFilePath, { encoding: 'binary' }).then((json) => {
                    var buf = new Buffer(JSON.stringify(json), 'binary');
                    var str = iconv.decode(buf, 'GBK');
                    resolve(eval(str))
                })
        })
    }

    async readExcelToJson(filePath) {
        try {
            const data = xlsx.parse(filePath)[0].data;

            // 处理数据，为没有分类的行填充最近的分类
            for (let i = data.length - 1; i >= 0; i--) {
                if (data[i].length < 2) {
                    // 如果当前行缺少分类，向上查找最近的分类
                    for (let j = i - 1; j >= 0; j--) {
                        if (data[j].length >= 2) {
                            data[i].push(data[j][1]); // 找到分类，添加到当前行
                            break;
                        }
                    }
                    // 如果遍历到开头还没找到分类，则使用默认值
                    if (data[i].length < 2) {
                        data[i].push('未知');
                    }
                }
            }
            const filteredData = data.filter(row => /^http/.test(row[0]));

            // 将数据转换为对象数组
            const jsonData = filteredData.map(row => ({
                url: row[0],
                category: row[1].split('-').map(str => str.trim())
            }));

            return jsonData;
        } catch (error) {
            console.error('Error reading Excel file:', error);
            throw error;
        }
    }

    async readExcelToJsonBase(filePath) {
        try {
            const data = xlsx.parse(filePath)[0].data;
            return data;
        } catch (error) {
            console.error('Error reading Excel file:', error);
            throw error;
        }
    }

}

module.exports = ExcelService;